{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "copyright"
      },
      "outputs": [],
      "source": [
        "# Copyright 2020 Google LLC\n",
        "#\n",
        "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "#     https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "title"
      },
      "source": [
        "# Training a TensorFlow model on BigQuery data\n",
        "\n",
        "<table align=\"left\">\n",
        "  <td>\n",
        "    <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/ai-platform-samples/blob/master/ai-platform-unified/notebooks/official/custom/custom-tabular-bq-managed-dataset.ipynb\">\n",
        "      <img src=\"https://cloud.google.com/ml-engine/images/colab-logo-32px.png\" alt=\"Colab logo\"> Run in Colab\n",
        "    </a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a href=\"https://github.com/GoogleCloudPlatform/ai-platform-samples/blob/master/ai-platform-unified/notebooks/official/custom/custom-tabular-bq-managed-dataset.ipynb\">\n",
        "      <img src=\"https://cloud.google.com/ml-engine/images/github-logo-32px.png\" alt=\"GitHub logo\">\n",
        "      View on GitHub\n",
        "    </a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "overview:custom"
      },
      "source": [
        "## Overview\n",
        "\n",
        "\n",
        "This tutorial demonstrates how to use the Vertex SDK for Python to train and deploy a custom tabular classification model for online prediction."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dataset:custom,cifar10,icn"
      },
      "source": [
        "### Dataset\n",
        "\n",
        "The dataset used for this tutorial is the penguins dataset from [BigQuery public datasets](https://cloud.google.com/bigquery/public-data). In this version of the dataset, you will use only the fields `culmen_length_mm`, `culmen_depth_mm`, `flipper_length_mm`, `body_mass_g` to predict the penguins species (`species`)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "objective:custom,training,online_prediction"
      },
      "source": [
        "### Objective\n",
        "\n",
        "In this notebook, you create a custom-trained model from a Python script in a Docker container using the Vertex SDK for Python, and then get a prediction from the deployed model by sending data. Alternatively, you can create custom-trained models using `gcloud` command-line tool, or online using the Cloud Console.\n",
        "\n",
        "The steps performed include:\n",
        "\n",
        "- Create a Vertex AI custom `TrainingPipeline` for training a model.\n",
        "- Train a TensorFlow model.\n",
        "- Deploy the `Model` resource to a serving `Endpoint` resource.\n",
        "- Make a prediction.\n",
        "- Undeploy the `Model` resource."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "costs"
      },
      "source": [
        "### Costs\n",
        "\n",
        "This tutorial uses billable components of Google Cloud:\n",
        "\n",
        "* Vertex AI\n",
        "* Cloud Storage\n",
        "\n",
        "Learn about [Vertex AI\n",
        "pricing](https://cloud.google.com/vertex-ai/pricing) and [Cloud Storage\n",
        "pricing](https://cloud.google.com/storage/pricing), and use the [Pricing\n",
        "Calculator](https://cloud.google.com/products/calculator/)\n",
        "to generate a cost estimate based on your projected usage."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "install_aip"
      },
      "source": [
        "## Installation\n",
        "\n",
        "Install the latest version of Vertex SDK for Python."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "1fd00fa70a2a"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "\n",
        "# The Google Cloud Notebook product has specific requirements\n",
        "IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists(\"/opt/deeplearning/metadata/env_version\")\n",
        "\n",
        "# Google Cloud Notebook requires dependencies to be installed with '--user'\n",
        "USER_FLAG = \"\"\n",
        "if IS_GOOGLE_CLOUD_NOTEBOOK:\n",
        "    USER_FLAG = \"--user\""
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "YsxCgt1zlugo"
      },
      "outputs": [],
      "source": [
        "! pip install {USER_FLAG} --upgrade google-cloud-aiplatform"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "install_storage"
      },
      "source": [
        "Install the latest version of *google-cloud-storage* library as well."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "qssss-KSlugo"
      },
      "outputs": [],
      "source": [
        "! pip install {USER_FLAG} -U google-cloud-storage"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Z3hYaR6gLEK-"
      },
      "source": [
        "Install the latest version of *google-cloud-bigquery* library as well."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "866ffc5cf763"
      },
      "outputs": [],
      "source": [
        "! pip install {USER_FLAG} -U \"google-cloud-bigquery[all]\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "restart"
      },
      "source": [
        "### Restart the kernel\n",
        "\n",
        "Once you've installed everything, you need to restart the notebook kernel so it can find the packages."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "bzPxhxS5lugp"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "\n",
        "if not os.getenv(\"IS_TESTING\"):\n",
        "    # Automatically restart kernel after installs\n",
        "    import IPython\n",
        "\n",
        "    app = IPython.Application.instance()\n",
        "    app.kernel.do_shutdown(True)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "before_you_begin"
      },
      "source": [
        "## Before you begin\n",
        "\n",
        "### Select a GPU runtime\n",
        "\n",
        "Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select \"Runtime --> Change runtime type > GPU\"\n",
        "\n",
        "### Set up your Google Cloud project\n",
        "\n",
        "**The following steps are required, regardless of your notebook environment.**\n",
        "\n",
        "1. [Select or create a Google Cloud project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
        "\n",
        "2. [Make sure that billing is enabled for your project](https://cloud.google.com/billing/docs/how-to/modify-project).\n",
        "\n",
        "3. [Enable the Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com).\n",
        "\n",
        "4. If you are running this notebook locally, you will need to install the [Cloud SDK](https://cloud.google.com/sdk).\n",
        "\n",
        "5. Enter your project ID in the cell below. Then run the cell to make sure the\n",
        "Cloud SDK uses the right project for all the commands in this notebook.\n",
        "\n",
        "**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "project_id"
      },
      "source": [
        "#### Set your project ID\n",
        "\n",
        "**If you don't know your project ID**, you might be able to get your project ID using `gcloud`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "autoset_project_id"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "\n",
        "PROJECT_ID = \"\"\n",
        "\n",
        "if not os.getenv(\"IS_TESTING\"):\n",
        "    # Get your Google Cloud project ID from gcloud\n",
        "    shell_output=!gcloud config list --format 'value(core.project)' 2>/dev/null\n",
        "    PROJECT_ID = shell_output[0]\n",
        "    print(\"Project ID: \", PROJECT_ID)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "set_project_id"
      },
      "source": [
        "Otherwise, set your project ID here."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "USd_pUT0lugr"
      },
      "outputs": [],
      "source": [
        "if PROJECT_ID == \"\" or PROJECT_ID is None:\n",
        "    PROJECT_ID = \"[your-project-id]\"  # @param {type:\"string\"}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "timestamp"
      },
      "source": [
        "#### Timestamp\n",
        "\n",
        "If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, create a timestamp for each instance session, and append it onto the name of resources you create in this tutorial."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "c-pX32xalugs"
      },
      "outputs": [],
      "source": [
        "from datetime import datetime\n",
        "\n",
        "TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gcp_authenticate"
      },
      "source": [
        "### Authenticate your Google Cloud account\n",
        "\n",
        "**If you are using Google Cloud Notebooks**, your environment is already\n",
        "authenticated. Skip this step.\n",
        "\n",
        "**If you are using Colab**, run the cell below and follow the instructions\n",
        "when prompted to authenticate your account via oAuth.\n",
        "\n",
        "**Otherwise**, follow these steps:\n",
        "\n",
        "1. In the Cloud Console, go to the [**Create service account key**\n",
        "   page](https://console.cloud.google.com/apis/credentials/serviceaccountkey).\n",
        "\n",
        "2. Click **Create service account**.\n",
        "\n",
        "3. In the **Service account name** field, enter a name, and\n",
        "   click **Create**.\n",
        "\n",
        "4. In the **Grant this service account access to project** section, click the **Role** drop-down list. Type \"Vertex AI\"\n",
        "into the filter box, and select\n",
        "   **Vertex AI Administrator**. Type \"Storage Object Admin\" into the filter box, and select **Storage Object Admin**.\n",
        "\n",
        "5. Click *Create*. A JSON file that contains your key downloads to your\n",
        "local environment.\n",
        "\n",
        "6. Enter the path to your service account key as the\n",
        "`GOOGLE_APPLICATION_CREDENTIALS` variable in the cell below and run the cell."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "vF60K5v1lugs"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "import sys\n",
        "\n",
        "# If you are running this notebook in Colab, run this cell and follow the\n",
        "# instructions to authenticate your GCP account. This provides access to your\n",
        "# Cloud Storage bucket and lets you submit training jobs and prediction\n",
        "# requests.\n",
        "\n",
        "# The Google Cloud Notebook product has specific requirements\n",
        "IS_GOOGLE_CLOUD_NOTEBOOK = os.path.exists(\"/opt/deeplearning/metadata/env_version\")\n",
        "\n",
        "# If on Google Cloud Notebooks, then don't execute this code\n",
        "if not IS_GOOGLE_CLOUD_NOTEBOOK:\n",
        "    if \"google.colab\" in sys.modules:\n",
        "        from google.colab import auth as google_auth\n",
        "\n",
        "        google_auth.authenticate_user()\n",
        "\n",
        "    # If you are running this notebook locally, replace the string below with the\n",
        "    # path to your service account key and run this cell to authenticate your GCP\n",
        "    # account.\n",
        "    elif not os.getenv(\"IS_TESTING\"):\n",
        "        %env GOOGLE_APPLICATION_CREDENTIALS ''"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bucket:custom"
      },
      "source": [
        "### Create a Cloud Storage bucket\n",
        "\n",
        "**The following steps are required, regardless of your notebook environment.**\n",
        "\n",
        "When you submit a training job using the Cloud SDK, you upload a Python package\n",
        "containing your training code to a Cloud Storage bucket. Vertex AI runs\n",
        "the code from this package. In this tutorial, Vertex AI also saves the\n",
        "trained model that results from your job in the same bucket. Using this model artifact, you can then\n",
        "create Vertex AI model and endpoint resources in order to serve\n",
        "online predictions.\n",
        "\n",
        "Set the name of your Cloud Storage bucket below. It must be unique across all\n",
        "Cloud Storage buckets.\n",
        "\n",
        "You may also change the `REGION` variable, which is used for operations\n",
        "throughout the rest of this notebook. Make sure to [choose a region where Vertex AI services are\n",
        "available](https://cloud.google.com/vertex-ai/docs/general/locations#available_regions). You may\n",
        "not use a Multi-Regional Storage bucket for training with Vertex AI."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "bucket"
      },
      "outputs": [],
      "source": [
        "BUCKET_NAME = \"\"  # @param {type:\"string\"}\n",
        "REGION = \"us-central1\"  # @param {type:\"string\"}"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "autoset_bucket"
      },
      "outputs": [],
      "source": [
        "if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"gs://[your-bucket-name]\":\n",
        "    BUCKET_NAME = \"gs://\" + PROJECT_ID + \"aip-\" + TIMESTAMP"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "create_bucket"
      },
      "source": [
        "**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Oz8J0vmSlugt"
      },
      "outputs": [],
      "source": [
        "! gsutil mb -l $REGION $BUCKET_NAME"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "validate_bucket"
      },
      "source": [
        "Finally, validate access to your Cloud Storage bucket by examining its contents:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "oadE10x2lugu"
      },
      "outputs": [],
      "source": [
        "! gsutil ls -al $BUCKET_NAME"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "setup_vars"
      },
      "source": [
        "## Set up variables\n",
        "\n",
        "Next, set up some variables used throughout the tutorial."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "import_aip"
      },
      "source": [
        "### Import Vertex SDK for Python\n",
        "\n",
        "Import the Vertex SDK for Python into your Python environment and initialize it."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "cNEiwLd0lugu"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "import sys\n",
        "\n",
        "from google.cloud import aiplatform\n",
        "from google.cloud.aiplatform import gapic as aip\n",
        "\n",
        "aiplatform.init(project=PROJECT_ID, location=REGION, staging_bucket=BUCKET_NAME)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "accelerators:training,prediction"
      },
      "source": [
        "### Set hardware accelerators\n",
        "\n",
        "You can set hardware accelerators for both training and prediction.\n",
        "\n",
        "Set the variables `TRAIN_GPU/TRAIN_NGPU` and `DEPLOY_GPU/DEPLOY_NGPU` to use a container image supporting a GPU and the number of GPUs allocated to the virtual machine (VM) instance. For example, to use a GPU container image with 4 Nvidia Tesla K80 GPUs allocated to each VM, you would specify:\n",
        "\n",
        "    (aip.AcceleratorType.NVIDIA_TESLA_K80, 4)\n",
        "\n",
        "See the [locations where accelerators are available](https://cloud.google.com/vertex-ai/docs/general/locations#accelerators).\n",
        "\n",
        "Otherwise specify `(None, None)` to use a container image to run on a CPU.\n",
        "\n",
        "Learn [which accelerators are available in your region.](https://cloud.google.com/vertex-ai/docs/general/locations#accelerators)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "xd5PLXDTlugv"
      },
      "outputs": [],
      "source": [
        "TRAIN_GPU, TRAIN_NGPU = (aip.AcceleratorType.NVIDIA_TESLA_K80, 1)\n",
        "\n",
        "DEPLOY_GPU, DEPLOY_NGPU = (aip.AcceleratorType.NVIDIA_TESLA_K80, 1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "container:training,prediction"
      },
      "source": [
        "### Set pre-built containers\n",
        "\n",
        "Vertex AI provides pre-built containers to run training and prediction.\n",
        "\n",
        "For the latest list, see [Pre-built containers for training](https://cloud.google.com/vertex-ai/docs/training/pre-built-containers) and [Pre-built containers for prediction](https://cloud.google.com/vertex-ai/docs/predictions/pre-built-containers)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "1u1mr18jlugv"
      },
      "outputs": [],
      "source": [
        "TRAIN_VERSION = \"tf-gpu.2-4\"\n",
        "DEPLOY_VERSION = \"tf2-gpu.2-4\"\n",
        "\n",
        "TRAIN_IMAGE = \"us-docker.pkg.dev/vertex-ai/training/{}:latest\".format(TRAIN_VERSION)\n",
        "DEPLOY_IMAGE = \"us-docker.pkg.dev/vertex-ai/prediction/{}:latest\".format(DEPLOY_VERSION)\n",
        "\n",
        "print(\"Training:\", TRAIN_IMAGE, TRAIN_GPU, TRAIN_NGPU)\n",
        "print(\"Deployment:\", DEPLOY_IMAGE, DEPLOY_GPU, DEPLOY_NGPU)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "machine:training,prediction"
      },
      "source": [
        "### Set machine types\n",
        "\n",
        "Next, set the machine types to use for training and prediction.\n",
        "\n",
        "- Set the variables `TRAIN_COMPUTE` and `DEPLOY_COMPUTE` to configure your compute resources for training and prediction.\n",
        " - `machine type`\n",
        "     - `n1-standard`: 3.75GB of memory per vCPU\n",
        "     - `n1-highmem`: 6.5GB of memory per vCPU\n",
        "     - `n1-highcpu`: 0.9 GB of memory per vCPU\n",
        " - `vCPUs`: number of \\[2, 4, 8, 16, 32, 64, 96 \\]\n",
        "\n",
        "*Note: The following is not supported for training:*\n",
        "\n",
        " - `standard`: 2 vCPUs\n",
        " - `highcpu`: 2, 4 and 8 vCPUs\n",
        "\n",
        "*Note: You may also use n2 and e2 machine types for training and deployment, but they do not support GPUs*.\n",
        "\n",
        "Learn [which machine types are available for training](https://cloud.google.com/vertex-ai/docs/training/configure-compute) and [which machine types are available for prediction](https://cloud.google.com/vertex-ai/docs/predictions/configure-compute)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "YAXwbqKKlugv"
      },
      "outputs": [],
      "source": [
        "MACHINE_TYPE = \"n1-standard\"\n",
        "\n",
        "VCPU = \"4\"\n",
        "TRAIN_COMPUTE = MACHINE_TYPE + \"-\" + VCPU\n",
        "print(\"Train machine type\", TRAIN_COMPUTE)\n",
        "\n",
        "MACHINE_TYPE = \"n1-standard\"\n",
        "\n",
        "VCPU = \"4\"\n",
        "DEPLOY_COMPUTE = MACHINE_TYPE + \"-\" + VCPU\n",
        "print(\"Deploy machine type\", DEPLOY_COMPUTE)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "59f24e7d2269"
      },
      "source": [
        "## Prepare the data\n",
        "\n",
        "To improve the convergence of the custom deep learning model, normalize the data. To prepare for this, calculate the mean and standard deviation for each numeric column.\n",
        "\n",
        "Pass these summary statistics to the training script to normalize the data before training. Later, during prediction, use these summary statistics again to normalize the testing data."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "890d562c6291"
      },
      "outputs": [],
      "source": [
        "BQ_SOURCE = \"bq://bigquery-public-data.ml_datasets.penguins\""
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "8e52b7832cd3"
      },
      "outputs": [],
      "source": [
        "import json\n",
        "\n",
        "import numpy as np\n",
        "# Calculate mean and std across all rows\n",
        "from google.cloud import bigquery\n",
        "\n",
        "NA_VALUES = [\"NA\", \".\"]\n",
        "\n",
        "# Set up BigQuery clients\n",
        "bqclient = bigquery.Client()\n",
        "\n",
        "\n",
        "# Download a table\n",
        "def download_table(bq_table_uri: str):\n",
        "    # Remove bq:// prefix if present\n",
        "    prefix = \"bq://\"\n",
        "    if bq_table_uri.startswith(prefix):\n",
        "        bq_table_uri = bq_table_uri[len(prefix) :]\n",
        "\n",
        "    table = bigquery.TableReference.from_string(bq_table_uri)\n",
        "    rows = bqclient.list_rows(\n",
        "        table,\n",
        "    )\n",
        "    return rows.to_dataframe()\n",
        "\n",
        "\n",
        "# Remove NA values\n",
        "def clean_dataframe(df):\n",
        "    return df.replace(to_replace=NA_VALUES, value=np.NaN).dropna()\n",
        "\n",
        "\n",
        "def calculate_mean_and_std(df):\n",
        "    # Calculate mean and std for each applicable column\n",
        "    mean_and_std = {}\n",
        "    dtypes = list(zip(df.dtypes.index, map(str, df.dtypes)))\n",
        "    # Normalize numeric columns.\n",
        "    for column, dtype in dtypes:\n",
        "        if dtype == \"float32\" or dtype == \"float64\":\n",
        "            mean_and_std[column] = {\n",
        "                \"mean\": df[column].mean(),\n",
        "                \"std\": df[column].std(),\n",
        "            }\n",
        "\n",
        "    return mean_and_std\n",
        "\n",
        "\n",
        "dataframe = download_table(BQ_SOURCE)\n",
        "dataframe = clean_dataframe(dataframe)\n",
        "mean_and_std = calculate_mean_and_std(dataframe)\n",
        "\n",
        "print(\"The mean and stds for each column are: \" + str(mean_and_std))\n",
        "\n",
        "# Write to a file\n",
        "MEAN_AND_STD_JSON_FILE = \"mean_and_std.json\"\n",
        "\n",
        "with open(MEAN_AND_STD_JSON_FILE, \"w\") as outfile:\n",
        "    json.dump(mean_and_std, outfile)\n",
        "\n",
        "# Save to the staging bucket\n",
        "! gsutil cp {MEAN_AND_STD_JSON_FILE} {BUCKET_NAME}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5c7732822757"
      },
      "source": [
        "## Create a managed tabular dataset from BigQuery dataset\n",
        "\n",
        "Your first step in training a model is to create a managed dataset instance."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "1d26b159106f"
      },
      "outputs": [],
      "source": [
        "dataset = aiplatform.TabularDataset.create(\n",
        "    display_name=\"sample-penguins\", bq_source=BQ_SOURCE\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "train_custom_model"
      },
      "source": [
        "## Train a model\n",
        "\n",
        "There are two ways you can train a model using a container image:\n",
        "\n",
        "- **Use a Vertex AI pre-built container**. If you use a pre-built training container, you must additionally specify a Python package to install into the container image. This Python package contains your training code.\n",
        "\n",
        "- **Use your own custom container image**. If you use your own container, the container image must contain your training code."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "train_custom_job_args"
      },
      "source": [
        "### Define the command args for the training script\n",
        "\n",
        "Prepare the command-line arguments to pass to your training script.\n",
        "- `args`: The command line arguments to pass to the corresponding Python module. In this example, they are:\n",
        "  - `\"--epochs=\" + EPOCHS`: The number of epochs for training.\n",
        "  - `\"--batch_size=\" + BATCH_SIZE`: The number of batch size for training.\n",
        "  - `\"--distribute=\" + TRAIN_STRATEGY` : The training distribution strategy to use for single or distributed training.\n",
        "     - `\"single\"`: single device.\n",
        "     - `\"mirror\"`: all GPU devices on a single compute instance.\n",
        "     - `\"multi\"`: all GPU devices on all compute instances.\n",
        "  - `\"--mean_and_std_json_file=\" + FILE_PATH`: The file on Google Cloud Storage with pre-calculated means and standard deviations."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "1npiDcUtlugw"
      },
      "outputs": [],
      "source": [
        "JOB_NAME = \"custom_job_\" + TIMESTAMP\n",
        "\n",
        "if not TRAIN_NGPU or TRAIN_NGPU < 2:\n",
        "    TRAIN_STRATEGY = \"single\"\n",
        "else:\n",
        "    TRAIN_STRATEGY = \"mirror\"\n",
        "\n",
        "EPOCHS = 20\n",
        "BATCH_SIZE = 10\n",
        "\n",
        "CMDARGS = [\n",
        "    \"--epochs=\" + str(EPOCHS),\n",
        "    \"--batch_size=\" + str(BATCH_SIZE),\n",
        "    \"--distribute=\" + TRAIN_STRATEGY,\n",
        "    \"--mean_and_std_json_file=\" + f\"{BUCKET_NAME}/{MEAN_AND_STD_JSON_FILE}\",\n",
        "]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "taskpy_contents"
      },
      "source": [
        "#### Training script\n",
        "\n",
        "In the next cell, write the contents of the training script, `task.py`. In summary, the script does the following:\n",
        "\n",
        "- Loads the data from the BigQuery table using the BigQuery Python client library.\n",
        "- Loads the pre-calculated mean and standard deviation from the Google Cloud Storage bucket.\n",
        "- Builds a model using TF.Keras model API.\n",
        "- Compiles the model (`compile()`).\n",
        "- Sets a training distribution strategy according to the argument `args.distribute`.\n",
        "- Trains the model (`fit()`) with epochs and batch size according to the arguments `args.epochs` and `args.batch_size`\n",
        "- Gets the directory where to save the model artifacts from the environment variable `AIP_MODEL_DIR`. This variable is [set by the training service](https://cloud.google.com/vertex-ai/docs/training/code-requirements#environment-variables).\n",
        "- Saves the trained model to the model directory."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "72rUqXNFlugx"
      },
      "outputs": [],
      "source": [
        "%%writefile task.py\n",
        "\n",
        "import argparse\n",
        "import tensorflow as tf\n",
        "import numpy as np\n",
        "import os\n",
        "\n",
        "import pandas as pd\n",
        "import tensorflow as tf\n",
        "\n",
        "from google.cloud import bigquery\n",
        "from google.cloud import storage\n",
        "\n",
        "# Read environmental variables\n",
        "training_data_uri = os.environ[\"AIP_TRAINING_DATA_URI\"]\n",
        "validation_data_uri = os.environ[\"AIP_VALIDATION_DATA_URI\"]\n",
        "test_data_uri = os.environ[\"AIP_TEST_DATA_URI\"]\n",
        "\n",
        "# Read args\n",
        "parser = argparse.ArgumentParser()\n",
        "parser.add_argument('--epochs', dest='epochs',\n",
        "                    default=10, type=int,\n",
        "                    help='Number of epochs.')\n",
        "parser.add_argument('--batch_size', dest='batch_size',\n",
        "                    default=10, type=int,\n",
        "                    help='Batch size.')\n",
        "parser.add_argument('--distribute', dest='distribute', type=str, default='single',\n",
        "                    help='Distributed training strategy.')\n",
        "parser.add_argument('--mean_and_std_json_file', dest='mean_and_std_json_file', type=str,\n",
        "                    help='GCS URI to the JSON file with pre-calculated column means and standard deviations.')\n",
        "args = parser.parse_args()\n",
        "\n",
        "def download_blob(bucket_name, source_blob_name, destination_file_name):\n",
        "    \"\"\"Downloads a blob from the bucket.\"\"\"\n",
        "    # bucket_name = \"your-bucket-name\"\n",
        "    # source_blob_name = \"storage-object-name\"\n",
        "    # destination_file_name = \"local/path/to/file\"\n",
        "\n",
        "    storage_client = storage.Client()\n",
        "\n",
        "    bucket = storage_client.bucket(bucket_name)\n",
        "\n",
        "    # Construct a client side representation of a blob.\n",
        "    # Note `Bucket.blob` differs from `Bucket.get_blob` as it doesn't retrieve\n",
        "    # any content from Google Cloud Storage. As we don't need additional data,\n",
        "    # using `Bucket.blob` is preferred here.\n",
        "    blob = bucket.blob(source_blob_name)\n",
        "    blob.download_to_filename(destination_file_name)\n",
        "\n",
        "    print(\n",
        "        \"Blob {} downloaded to {}.\".format(\n",
        "            source_blob_name, destination_file_name\n",
        "        )\n",
        "    )\n",
        "\n",
        "def extract_bucket_and_prefix_from_gcs_path(gcs_path: str):\n",
        "    \"\"\"Given a complete GCS path, return the bucket name and prefix as a tuple.\n",
        "\n",
        "    Example Usage:\n",
        "\n",
        "        bucket, prefix = extract_bucket_and_prefix_from_gcs_path(\n",
        "            \"gs://example-bucket/path/to/folder\"\n",
        "        )\n",
        "\n",
        "        # bucket = \"example-bucket\"\n",
        "        # prefix = \"path/to/folder\"\n",
        "\n",
        "    Args:\n",
        "        gcs_path (str):\n",
        "            Required. A full path to a Google Cloud Storage folder or resource.\n",
        "            Can optionally include \"gs://\" prefix or end in a trailing slash \"/\".\n",
        "\n",
        "    Returns:\n",
        "        Tuple[str, Optional[str]]\n",
        "            A (bucket, prefix) pair from provided GCS path. If a prefix is not\n",
        "            present, a None will be returned in its place.\n",
        "    \"\"\"\n",
        "    if gcs_path.startswith(\"gs://\"):\n",
        "        gcs_path = gcs_path[5:]\n",
        "    if gcs_path.endswith(\"/\"):\n",
        "        gcs_path = gcs_path[:-1]\n",
        "\n",
        "    gcs_parts = gcs_path.split(\"/\", 1)\n",
        "    gcs_bucket = gcs_parts[0]\n",
        "    gcs_blob_prefix = None if len(gcs_parts) == 1 else gcs_parts[1]\n",
        "\n",
        "    return (gcs_bucket, gcs_blob_prefix)\n",
        "\n",
        "# Download means and std\n",
        "def download_mean_and_std(mean_and_std_json_file):\n",
        "    \"\"\"Download mean and std for each column\"\"\"\n",
        "    import json\n",
        "    \n",
        "    bucket, file_path = extract_bucket_and_prefix_from_gcs_path(mean_and_std_json_file)\n",
        "    download_blob(bucket_name=bucket, source_blob_name=file_path, destination_file_name=file_path)\n",
        "    \n",
        "    with open(file_path, 'r') as file:\n",
        "        return json.loads(file.read())\n",
        "    \n",
        "mean_and_std = download_mean_and_std(args.mean_and_std_json_file)\n",
        "\n",
        "# Single Machine, single compute device\n",
        "if args.distribute == 'single':\n",
        "    if tf.test.is_gpu_available():\n",
        "        strategy = tf.distribute.OneDeviceStrategy(device=\"/gpu:0\")\n",
        "    else:\n",
        "        strategy = tf.distribute.OneDeviceStrategy(device=\"/cpu:0\")\n",
        "# Single Machine, multiple compute device\n",
        "elif args.distribute == 'mirror':\n",
        "    strategy = tf.distribute.MirroredStrategy()\n",
        "# Multiple Machine, multiple compute device\n",
        "elif args.distribute == 'multi':\n",
        "    strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()\n",
        "\n",
        "# Set up training variables\n",
        "LABEL_COLUMN = \"species\"\n",
        "UNUSED_COLUMNS = []\n",
        "NA_VALUES = [\"NA\", \".\"]\n",
        "\n",
        "# Possible categorical values\n",
        "SPECIES = ['Adelie Penguin (Pygoscelis adeliae)',\n",
        "           'Chinstrap penguin (Pygoscelis antarctica)',\n",
        "           'Gentoo penguin (Pygoscelis papua)']\n",
        "ISLANDS = ['Dream', 'Biscoe', 'Torgersen']\n",
        "SEXES = ['FEMALE', 'MALE']\n",
        "\n",
        "# Set up BigQuery clients\n",
        "bqclient = bigquery.Client()\n",
        "\n",
        "# Download a table\n",
        "def download_table(bq_table_uri: str):\n",
        "    # Remove bq:// prefix if present\n",
        "    prefix = \"bq://\"\n",
        "    if bq_table_uri.startswith(prefix):\n",
        "        bq_table_uri = bq_table_uri[len(prefix):]\n",
        "\n",
        "    table = bigquery.TableReference.from_string(bq_table_uri)\n",
        "    rows = bqclient.list_rows(\n",
        "        table,\n",
        "    )\n",
        "    return rows.to_dataframe(create_bqstorage_client=False)\n",
        "\n",
        "\n",
        "df_train = download_table(training_data_uri)\n",
        "df_validation = download_table(validation_data_uri)\n",
        "df_test = download_table(test_data_uri)\n",
        "\n",
        "# Remove NA values\n",
        "def clean_dataframe(df):\n",
        "    return df.replace(to_replace=NA_VALUES, value=np.NaN).dropna()\n",
        "\n",
        "\n",
        "df_train = clean_dataframe(df_train)\n",
        "#     df_validation = clean_dataframe(df_validation)\n",
        "df_validation = clean_dataframe(df_validation)\n",
        "\n",
        "_CATEGORICAL_TYPES = {\n",
        "    \"island\": pd.api.types.CategoricalDtype(categories=ISLANDS),\n",
        "    \"species\": pd.api.types.CategoricalDtype(categories=SPECIES),\n",
        "    \"sex\": pd.api.types.CategoricalDtype(categories=SEXES),\n",
        "}\n",
        "\n",
        "\n",
        "def standardize(df, mean_and_std):\n",
        "    \"\"\"Scales numerical columns using their means and standard deviation to get\n",
        "    z-scores: the mean of each numerical column becomes 0, and the standard\n",
        "    deviation becomes 1. This can help the model converge during training.\n",
        "\n",
        "    Args:\n",
        "      df: Pandas df\n",
        "\n",
        "    Returns:\n",
        "      Input df with the numerical columns scaled to z-scores\n",
        "    \"\"\"\n",
        "    dtypes = list(zip(df.dtypes.index, map(str, df.dtypes)))\n",
        "    # Normalize numeric columns.\n",
        "    for column, dtype in dtypes:\n",
        "        if dtype == \"float32\":\n",
        "            df[column] -= mean_and_std[column][\"mean\"]\n",
        "            df[column] /= mean_and_std[column][\"std\"]\n",
        "    return df\n",
        "\n",
        "def preprocess(df):\n",
        "    \"\"\"Converts categorical features to numeric. Removes unused columns.\n",
        "\n",
        "    Args:\n",
        "      df: Pandas df with raw data\n",
        "\n",
        "    Returns:\n",
        "      df with preprocessed data\n",
        "    \"\"\"\n",
        "    df = df.drop(columns=UNUSED_COLUMNS)\n",
        "\n",
        "    # Drop rows with NaN's\n",
        "    df = df.dropna()\n",
        "\n",
        "    # Convert integer valued (numeric) columns to floating point\n",
        "    numeric_columns = df.select_dtypes([\"int32\", \"float32\", \"float64\"]).columns\n",
        "    df[numeric_columns] = df[numeric_columns].astype(\"float32\")\n",
        "\n",
        "    # Convert categorical columns to numeric\n",
        "    cat_columns = df.select_dtypes([\"object\"]).columns\n",
        "\n",
        "    df[cat_columns] = df[cat_columns].apply(\n",
        "        lambda x: x.astype(_CATEGORICAL_TYPES[x.name])\n",
        "    )\n",
        "    df[cat_columns] = df[cat_columns].apply(lambda x: x.cat.codes)\n",
        "    return df\n",
        "\n",
        "\n",
        "def convert_dataframe_to_dataset(\n",
        "    df_train,\n",
        "    df_validation,\n",
        "    mean_and_std\n",
        "):\n",
        "    df_train = preprocess(df_train)\n",
        "    df_validation = preprocess(df_validation)\n",
        "\n",
        "    df_train_x, df_train_y = df_train, df_train.pop(LABEL_COLUMN)\n",
        "    df_validation_x, df_validation_y = df_validation, df_validation.pop(LABEL_COLUMN)\n",
        "\n",
        "    # Join train_x and eval_x to normalize on overall means and standard\n",
        "    # deviations. Then separate them again.\n",
        "    all_x = pd.concat([df_train_x, df_validation_x], keys=[\"train\", \"eval\"])\n",
        "    all_x = standardize(all_x, mean_and_std)\n",
        "    df_train_x, df_validation_x = all_x.xs(\"train\"), all_x.xs(\"eval\")\n",
        "\n",
        "    y_train = np.asarray(df_train_y).astype(\"float32\")\n",
        "    y_validation = np.asarray(df_validation_y).astype(\"float32\")\n",
        "\n",
        "    # Convert to numpy representation\n",
        "    x_train = np.asarray(df_train_x)\n",
        "    x_test = np.asarray(df_validation_x)\n",
        "\n",
        "    # Convert to one-hot representation\n",
        "    y_train = tf.keras.utils.to_categorical(y_train, num_classes=len(SPECIES))\n",
        "    y_validation = tf.keras.utils.to_categorical(y_validation, num_classes=len(SPECIES))\n",
        "\n",
        "    dataset_train = tf.data.Dataset.from_tensor_slices((x_train, y_train))\n",
        "    dataset_validation = tf.data.Dataset.from_tensor_slices((x_test, y_validation))\n",
        "    return (dataset_train, dataset_validation)\n",
        "\n",
        "# Create datasets\n",
        "dataset_train, dataset_validation = convert_dataframe_to_dataset(df_train, df_validation, mean_and_std)\n",
        "\n",
        "# Shuffle train set\n",
        "dataset_train = dataset_train.shuffle(len(df_train))\n",
        "\n",
        "def create_model(num_features):\n",
        "    # Create model\n",
        "    Dense = tf.keras.layers.Dense\n",
        "    model = tf.keras.Sequential(\n",
        "        [\n",
        "            Dense(\n",
        "                100,\n",
        "                activation=tf.nn.relu,\n",
        "                kernel_initializer=\"uniform\",\n",
        "                input_dim=num_features,\n",
        "            ),\n",
        "            Dense(75, activation=tf.nn.relu),\n",
        "            Dense(50, activation=tf.nn.relu),\n",
        "            Dense(25, activation=tf.nn.relu),\n",
        "            Dense(3, activation=tf.nn.softmax),\n",
        "        ]\n",
        "    )\n",
        "    \n",
        "    # Compile Keras model\n",
        "    optimizer = tf.keras.optimizers.RMSprop(lr=0.001)\n",
        "    model.compile(\n",
        "        loss=\"categorical_crossentropy\", metrics=[\"accuracy\"], optimizer=optimizer\n",
        "    )\n",
        "    \n",
        "    return model\n",
        "\n",
        "# Create the model\n",
        "with strategy.scope():\n",
        "    model = create_model(num_features=dataset_train._flat_shapes[0].dims[0].value)\n",
        "\n",
        "# Set up datasets\n",
        "NUM_WORKERS = strategy.num_replicas_in_sync\n",
        "# Here the batch size scales up by number of workers since\n",
        "# `tf.data.Dataset.batch` expects the global batch size.\n",
        "GLOBAL_BATCH_SIZE = args.batch_size * NUM_WORKERS\n",
        "dataset_train = dataset_train.batch(GLOBAL_BATCH_SIZE)\n",
        "dataset_validation = dataset_validation.batch(GLOBAL_BATCH_SIZE)\n",
        "\n",
        "# Train the model\n",
        "model.fit(dataset_train, epochs=args.epochs, validation_data=dataset_validation)\n",
        "\n",
        "tf.saved_model.save(model, os.environ[\"AIP_MODEL_DIR\"])\n",
        "\n",
        "df_test.head()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "train_custom_job"
      },
      "source": [
        "### Train the model\n",
        "\n",
        "Define your custom `TrainingPipeline` on Vertex AI.\n",
        "\n",
        "Use the `CustomTrainingJob` class to define the `TrainingPipeline`. The class takes the following parameters:\n",
        "\n",
        "- `display_name`: The user-defined name of this training pipeline.\n",
        "- `script_path`: The local path to the training script.\n",
        "- `container_uri`: The URI of the training container image.\n",
        "- `requirements`: The list of Python package dependencies of the script.\n",
        "- `model_serving_container_image_uri`: The URI of a container that can serve predictions for your model — either a pre-built container or a custom container.\n",
        "\n",
        "Use the `run` function to start training. The function takes the following parameters:\n",
        "\n",
        "- `args`: The command line arguments to be passed to the Python script.\n",
        "- `replica_count`: The number of worker replicas.\n",
        "- `model_display_name`: The display name of the `Model` if the script produces a managed `Model`.\n",
        "- `machine_type`: The type of machine to use for training.\n",
        "- `accelerator_type`: The hardware accelerator type.\n",
        "- `accelerator_count`: The number of accelerators to attach to a worker replica.\n",
        "\n",
        "The `run` function creates a training pipeline that trains and creates a `Model` object. After the training pipeline completes, the `run` function returns the `Model` object."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "mxIxvDdglugx"
      },
      "outputs": [],
      "source": [
        "job = aiplatform.CustomTrainingJob(\n",
        "    display_name=JOB_NAME,\n",
        "    script_path=\"task.py\",\n",
        "    container_uri=TRAIN_IMAGE,\n",
        "    requirements=[\"google-cloud-bigquery>=2.20.0\"],\n",
        "    model_serving_container_image_uri=DEPLOY_IMAGE,\n",
        ")\n",
        "\n",
        "MODEL_DISPLAY_NAME = \"penguins-\" + TIMESTAMP\n",
        "\n",
        "# Start the training\n",
        "if TRAIN_GPU:\n",
        "    model = job.run(\n",
        "        dataset=dataset,\n",
        "        model_display_name=MODEL_DISPLAY_NAME,\n",
        "        bigquery_destination=f\"bq://{PROJECT_ID}\",\n",
        "        args=CMDARGS,\n",
        "        replica_count=1,\n",
        "        machine_type=TRAIN_COMPUTE,\n",
        "        accelerator_type=TRAIN_GPU.name,\n",
        "        accelerator_count=TRAIN_NGPU,\n",
        "    )\n",
        "else:\n",
        "    model = job.run(\n",
        "        dataset=dataset,\n",
        "        model_display_name=MODEL_DISPLAY_NAME,\n",
        "        bigquery_destination=f\"bq://{PROJECT_ID}\",\n",
        "        args=CMDARGS,\n",
        "        replica_count=1,\n",
        "        machine_type=TRAIN_COMPUTE,\n",
        "        accelerator_count=0,\n",
        "    )"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "deploy_model:dedicated"
      },
      "source": [
        "### Deploy the model\n",
        "\n",
        "Before you use your model to make predictions, you must deploy it to an `Endpoint`. You can do this by calling the `deploy` function on the `Model` resource. This will do two things:\n",
        "\n",
        "1. Create an `Endpoint` resource for deploying the `Model` resource to.\n",
        "2. Deploy the `Model` resource to the `Endpoint` resource.\n",
        "\n",
        "\n",
        "The function takes the following parameters:\n",
        "\n",
        "- `deployed_model_display_name`: A human readable name for the deployed model.\n",
        "- `traffic_split`: Percent of traffic at the endpoint that goes to this model, which is specified as a dictionary of one or more key/value pairs.\n",
        "   - If only one model, then specify `{ \"0\": 100 }`, where \"0\" refers to this model being uploaded and 100 means 100% of the traffic.\n",
        "   - If there are existing models on the endpoint, for which the traffic will be split, then use `model_id` to specify `{ \"0\": percent, model_id: percent, ... }`, where `model_id` is the ID of an existing `DeployedModel` on the endpoint. The percentages must add up to 100.\n",
        "- `machine_type`: The type of machine to use for training.\n",
        "- `accelerator_type`: The hardware accelerator type.\n",
        "- `accelerator_count`: The number of accelerators to attach to a worker replica.\n",
        "- `starting_replica_count`: The number of compute instances to initially provision.\n",
        "- `max_replica_count`: The maximum number of compute instances to scale to. In this tutorial, only one instance is provisioned.\n",
        "\n",
        "### Traffic split\n",
        "\n",
        "The `traffic_split` parameter is specified as a Python dictionary. You can deploy more than one instance of your model to an endpoint, and then set the percentage of traffic that goes to each instance.\n",
        "\n",
        "You can use a traffic split to introduce a new model gradually into production. For example, if you had one existing model in production with 100% of the traffic, you could deploy a new model to the same endpoint, direct 10% of traffic to it, and reduce the original model's traffic to 90%. This allows you to monitor the new model's performance while minimizing the distruption to the majority of users.\n",
        "\n",
        "### Compute instance scaling\n",
        "\n",
        "You can specify a single instance (or node) to serve your online prediction requests. This tutorial uses a single node, so the variables `MIN_NODES` and `MAX_NODES` are both set to `1`.\n",
        "\n",
        "If you want to use multiple nodes to serve your online prediction requests, set `MAX_NODES` to the maximum number of nodes you want to use. Vertex AI autoscales the number of nodes used to serve your predictions, up to the maximum number you set. Refer to the [pricing page](https://cloud.google.com/vertex-ai/pricing#prediction-prices) to understand the costs of autoscaling with multiple nodes.\n",
        "\n",
        "### Endpoint\n",
        "\n",
        "The method will block until the model is deployed and eventually return an `Endpoint` object. If this is the first time a model is deployed to the endpoint, it may take a few additional minutes to complete provisioning of resources."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "WMH7GrYMlugy"
      },
      "outputs": [],
      "source": [
        "DEPLOYED_NAME = \"penguins_deployed-\" + TIMESTAMP\n",
        "\n",
        "TRAFFIC_SPLIT = {\"0\": 100}\n",
        "\n",
        "MIN_NODES = 1\n",
        "MAX_NODES = 1\n",
        "\n",
        "if DEPLOY_GPU:\n",
        "    endpoint = model.deploy(\n",
        "        deployed_model_display_name=DEPLOYED_NAME,\n",
        "        traffic_split=TRAFFIC_SPLIT,\n",
        "        machine_type=DEPLOY_COMPUTE,\n",
        "        accelerator_type=DEPLOY_GPU.name,\n",
        "        accelerator_count=DEPLOY_NGPU,\n",
        "        min_replica_count=MIN_NODES,\n",
        "        max_replica_count=MAX_NODES,\n",
        "    )\n",
        "else:\n",
        "    endpoint = model.deploy(\n",
        "        deployed_model_display_name=DEPLOYED_NAME,\n",
        "        traffic_split=TRAFFIC_SPLIT,\n",
        "        machine_type=DEPLOY_COMPUTE,\n",
        "        accelerator_type=DEPLOY_COMPUTE.name,\n",
        "        accelerator_count=0,\n",
        "        min_replica_count=MIN_NODES,\n",
        "        max_replica_count=MAX_NODES,\n",
        "    )"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "make_prediction"
      },
      "source": [
        "## Make an online prediction request\n",
        "\n",
        "Send an online prediction request to your deployed model."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "get_test_item:test"
      },
      "source": [
        "### Prepare test data\n",
        "\n",
        "Prepare test data by normalizing it and converting categorical values to numeric values.\n",
        "You must normalize these values in the same way that your normalized training data.\n",
        "\n",
        "In this example, perform testing with the same dataset that you used for training. In practice, you generally want to use a separate test dataset to verify your results."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "e3a2449cfcf1"
      },
      "outputs": [],
      "source": [
        "import pandas as pd\n",
        "from google.cloud import bigquery\n",
        "\n",
        "UNUSED_COLUMNS = []\n",
        "LABEL_COLUMN = \"species\"\n",
        "\n",
        "# Possible categorical values\n",
        "SPECIES = [\n",
        "    \"Adelie Penguin (Pygoscelis adeliae)\",\n",
        "    \"Chinstrap penguin (Pygoscelis antarctica)\",\n",
        "    \"Gentoo penguin (Pygoscelis papua)\",\n",
        "]\n",
        "ISLANDS = [\"Dream\", \"Biscoe\", \"Torgersen\"]\n",
        "SEXES = [\"FEMALE\", \"MALE\"]\n",
        "\n",
        "_CATEGORICAL_TYPES = {\n",
        "    \"island\": pd.api.types.CategoricalDtype(categories=ISLANDS),\n",
        "    \"species\": pd.api.types.CategoricalDtype(categories=SPECIES),\n",
        "    \"sex\": pd.api.types.CategoricalDtype(categories=SEXES),\n",
        "}\n",
        "\n",
        "\n",
        "def standardize(df, mean_and_std):\n",
        "    \"\"\"Scales numerical columns using their means and standard deviation to get\n",
        "    z-scores: the mean of each numerical column becomes 0, and the standard\n",
        "    deviation becomes 1. This can help the model converge during training.\n",
        "\n",
        "    Args:\n",
        "      df: Pandas df\n",
        "\n",
        "    Returns:\n",
        "      Input df with the numerical columns scaled to z-scores\n",
        "    \"\"\"\n",
        "    dtypes = list(zip(df.dtypes.index, map(str, df.dtypes)))\n",
        "    # Normalize numeric columns.\n",
        "    for column, dtype in dtypes:\n",
        "        if dtype == \"float32\":\n",
        "            df[column] -= mean_and_std[column][\"mean\"]\n",
        "            df[column] /= mean_and_std[column][\"std\"]\n",
        "    return df\n",
        "\n",
        "\n",
        "def preprocess(df, mean_and_std):\n",
        "    \"\"\"Converts categorical features to numeric. Removes unused columns.\n",
        "\n",
        "    Args:\n",
        "      df: Pandas df with raw data\n",
        "\n",
        "    Returns:\n",
        "      df with preprocessed data\n",
        "    \"\"\"\n",
        "    df = df.drop(columns=UNUSED_COLUMNS)\n",
        "\n",
        "    # Drop rows with NaN's\n",
        "    df = df.dropna()\n",
        "\n",
        "    # Convert integer valued (numeric) columns to floating point\n",
        "    numeric_columns = df.select_dtypes([\"int32\", \"float32\", \"float64\"]).columns\n",
        "    df[numeric_columns] = df[numeric_columns].astype(\"float32\")\n",
        "\n",
        "    # Convert categorical columns to numeric\n",
        "    cat_columns = df.select_dtypes([\"object\"]).columns\n",
        "\n",
        "    df[cat_columns] = df[cat_columns].apply(\n",
        "        lambda x: x.astype(_CATEGORICAL_TYPES[x.name])\n",
        "    )\n",
        "    df[cat_columns] = df[cat_columns].apply(lambda x: x.cat.codes)\n",
        "    return df\n",
        "\n",
        "\n",
        "def convert_dataframe_to_list(df, mean_and_std):\n",
        "    df = preprocess(df, mean_and_std)\n",
        "\n",
        "    df_x, df_y = df, df.pop(LABEL_COLUMN)\n",
        "\n",
        "    # Normalize on overall means and standard deviations.\n",
        "    df = standardize(df, mean_and_std)\n",
        "\n",
        "    y = np.asarray(df_y).astype(\"float32\")\n",
        "\n",
        "    # Convert to numpy representation\n",
        "    x = np.asarray(df_x)\n",
        "\n",
        "    # Convert to one-hot representation\n",
        "    return x.tolist(), y.tolist()\n",
        "\n",
        "\n",
        "x_test, y_test = convert_dataframe_to_list(dataframe, mean_and_std)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "send_prediction_request:image"
      },
      "source": [
        "### Send the prediction request\n",
        "\n",
        "Now that you have test data, you can use it to send a prediction request. Use the `Endpoint` object's `predict` function, which takes the following parameters:\n",
        "\n",
        "- `instances`: A list of penguin measurement instances. According to your custom model, each instance should be an array of numbers. You prepared this list in the previous step.\n",
        "\n",
        "The `predict` function returns a list, where each element in the list corresponds to the an instance in the request. In the output for each prediction, you will see the following:\n",
        "\n",
        "- Confidence level for the prediction (`predictions`), between 0 and 1, for each of the ten classes.\n",
        "\n",
        "You can then run a quick evaluation on the prediction results:\n",
        "1. `np.argmax`: Convert each list of confidence levels to a label\n",
        "2. Compare the predicted labels to the actual labels\n",
        "3. Calculate `accuracy` as `correct/total`"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "6e20473b09f5"
      },
      "outputs": [],
      "source": [
        "predictions = endpoint.predict(instances=x_test)\n",
        "y_predicted = np.argmax(predictions.predictions, axis=1)\n",
        "\n",
        "correct = sum(y_predicted == np.array(y_test))\n",
        "accuracy = len(y_predicted)\n",
        "print(\n",
        "    f\"Correct predictions = {correct}, Total predictions = {accuracy}, Accuracy = {correct/accuracy}\"\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "undeploy_model"
      },
      "source": [
        "## Undeploy the model\n",
        "\n",
        "To undeploy your `Model` resource from the serving `Endpoint` resource, use the endpoint's `undeploy` method with the following parameter:\n",
        "\n",
        "- `deployed_model_id`: The model deployment identifier returned by the endpoint service when the `Model` resource was deployed. You can retrieve the deployed models using the endpoint's `deployed_models` property.\n",
        "\n",
        "Since this is the only deployed model on the `Endpoint` resource, you can omit `traffic_split`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "khPSAO1tlug0"
      },
      "outputs": [],
      "source": [
        "deployed_model_id = endpoint.list_models()[0].id\n",
        "endpoint.undeploy(deployed_model_id=deployed_model_id)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cleanup:custom"
      },
      "source": [
        "## Cleaning up\n",
        "\n",
        "To clean up all Google Cloud resources used in this project, you can [delete the Google Cloud project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects) you used for the tutorial.\n",
        "\n",
        "Otherwise, you can delete the individual resources you created in this tutorial:\n",
        "\n",
        "- Training Job\n",
        "- Model\n",
        "- Endpoint\n",
        "- Cloud Storage Bucket"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "NNmebHf7lug0"
      },
      "outputs": [],
      "source": [
        "delete_training_job = True\n",
        "delete_model = True\n",
        "delete_endpoint = True\n",
        "\n",
        "# Warning: Setting this to true will delete everything in your bucket\n",
        "delete_bucket = False\n",
        "\n",
        "# Delete the training job\n",
        "job.delete()\n",
        "\n",
        "# Delete the model\n",
        "model.delete()\n",
        "\n",
        "# Delete the endpoint\n",
        "endpoint.delete()\n",
        "\n",
        "if delete_bucket and \"BUCKET_NAME\" in globals():\n",
        "    ! gsutil -m rm -r $BUCKET_NAME"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "name": "custom-tabular-bq-managed-dataset.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
